<?php

namespace app\admin\controller\check;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Db;
use think\Exception;

/**
 * 课程管理
 *
 * @icon fa fa-user
 */
class Cleaner extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['getDownStatus'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $service_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Cleaner');
        $this->service_model = model('Service');
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch =true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where = [];
            $filter = $this->request->get('filter');
            $offset = $this->request->get('offset');
            $order = $this->request->get('order');
            $sort = $this->request->get('sort');
            $limit = $this->request->get('limit');
            $filter = json_decode($filter,true);
            $string = '';
            foreach ($filter as $w=>$v){
                if($w=='add_time'){
                    $time_arr = explode(' - ',$v);
                    $where['add_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1])]];
                    //  $where_new['end_time'] = ['<=',$time_arr[1]];
                }else if($w=='schedule.type_name'){
                    $where['tg_type'] = $v;
                    //  $where_new['end_time'] = ['<=',$time_arr[1]];
                }else if($w=='uid' || $w=='status'){
                    $where[$w] = $v;
                }else if($w=='cleaner_name' || $w=='phone' || $w=='housing'){
                    $where[$w] = ['like','%'.$v.'%'];
                }else if($w=='province' || $w=='city' || $w=='area'){
                    $string.= $v.'-';
                }
            }
            if($string){
                $string = substr($string, 0, -1);
                $where['address'] = $string;
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset,$limit)
                ->select();
            // 获取当前年份和月份
            $year = date('Y');
            $month = date('m');
            foreach ($list as $w=>&$v){
               $v['end_service_num'] = Db::name('store_order_service')
                    ->where(['cleaning_id'=>$v['uid']])
                    ->where(['cleaning_end_time'=>['between',[mktime(0, 0, 0, $month, 1, $year),mktime(0, 0, 0, $month + 1, 0, $year) - 1]]])
                    ->count();
                $v['now_service_num'] = Db::name('store_order_service')
                    ->where(['cleaning_id'=>$v['uid']])
                    ->where(['status'=>['in',[1,2]]])
                    ->count();
            }
            $sql = $this->model->getLastSql();
            $result = array("total" => $count, "rows" => $list,'sql'=>$sql);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['add_time'] = time();
            $user_info  = Db::name('user')->where(['phone'=>$params['phone']])->find();
            if(!$user_info){
                $this->error('该手机号尚未注册小程序');
            }
            $params['uid'] = $user_info['uid'];
            $params['address'] = str_replace('/','-',$params['address']);
            $res = $this->model->insert($params);
            if ($res){
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['address'] = str_replace('/','-',$params['address']);
                    $params['up_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['address'] = str_replace('-','/',$row['address']);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id'=>$row['id']])->delete();
        $this->success();
    }

    /**
     * 详情
     */
    public function detail($ids=''){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['update_time'] = time();
                    $params['admin_id'] = $this->auth->id;
                    $image_arr = explode('aliyuncs.com',$params['logo']);
                    if($params['logo']){
                        $params['logo'] = $image_arr[1];
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 获取当前年份和月份
        $year = date('Y');
        $month = date('m');
        $row['total_end_service_num'] = Db::name('store_order_service')
            ->where(['cleaning_id'=>$row['uid']])
            ->count();
        $row['end_service_num'] = Db::name('store_order_service')
            ->where(['cleaning_id'=>$row['uid']])
            ->where(['cleaning_end_time'=>['between',[mktime(0, 0, 0, $month, 1, $year),mktime(0, 0, 0, $month + 1, 0, $year) - 1]]])
            ->count();
        $row['today_end_service_num'] = Db::name('store_order_service')
            ->where(['cleaning_id'=>$row['uid']])
            ->where(['cleaning_end_time'=>['between',[strtotime(date('Y-m-d 00:00:00')),strtotime(date('Y-m-d 23:59:59'))]]])
            ->count();
        $row['now_service_num'] = Db::name('store_order_service')
            ->where(['cleaning_id'=>$row['uid']])
            ->where(['status'=>['in',[1,2]]])
            ->count();
        if($row['status'] == 1){
            $row['status_text'] = '上线';
        }else if($row['status'] == 2){
            $row['status_text'] = '下线';
        }else{
            $row['status_text'] = '离职';
        }
        $row['add_time'] = date('Y-m-d 00:00:00',$row['add_time']);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 改变状态
     */
    public function change_status($ids){

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        try{
            $status = $this->request->get('status');
            Db::startTrans();
            $where = [
                'id'=>$ids,
            ];
            $updata = [
                'status'=>$status,
                'up_time'=>time()
            ];
            if($status==1){
                $content = '上线成功';
            }else if($status==2){
                $content = '下线成功';
            }else{
                $content = '离职成功';
            }
            $result = $this->model->where($where)->update($updata);
            if($result){
                if($status > 1){
                    $service_where = [
                        'cleaning_id'=>$ids,
                        'status'=>1,
                    ];
                    $this->service_model->where($service_where)->update(['cleaning_id'=>0,'push_time'=>0]); //请假后，清空保洁员信息
                }
                Db::commit();
                $this->success($content);
            }

        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }


    /**
     * 批量下线
     */
    public function do_most_down($ids=''){
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $check_id = $this->request->get("check_id");
            if(!$check_id){
                $this->error('尚未选择任何一笔订单');
            }
           // var_dump($check_id);
            if ($params) {
                try {
                    $check_id_arr = explode(',',$check_id);
                    $params['up_time'] = time();
                    $params['status'] = 2;
                    unset($params['salesman_id']);
                    if($params['down_reason'] == 2 && $params['down_remark'] == ''){
                        $this->error('补充说明不能为空');
                    }
                    // $params['salesman_id'] = time();
                    $result =  $this->model->where(['id'=>['in',$check_id_arr]])->update($params);
                    if ($result !== false) {
                        $this->success();
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 批量上线
     */
    public function do_most_up($ids=''){
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $check_id = $this->request->post("check_id");
            if(!$check_id){
                $this->error('尚未选择任何一笔订单');
            }
            try {
                $check_id_arr = explode(',',$check_id);
                $params['up_time'] = time();
                $params['status'] =1;
                // $params['salesman_id'] = time();
                $result =  $this->model->where(['id'=>['in',$check_id_arr]])->update($params);
                if ($result !== false) {
                    $this->success();
                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 批量离职
     */
    public function do_most_leave($ids=''){
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $check_id = $this->request->post("check_id");
            if(!$check_id){
                $this->error('尚未选择任何一笔订单');
            }
            try {
                $check_id_arr = explode(',',$check_id);
                $params['up_time'] = time();
                $params['status'] =3;
                // $params['salesman_id'] = time();
                $result =  $this->model->where(['id'=>['in',$check_id_arr]])->update($params);
                if ($result !== false) {
                    $this->success();
                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            } catch (\think\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    public function getDownStatus(){
        $new_list = [
            [
                'id'=>0,
                'title'=>'请选择原因',
            ],
            [
                'id'=>1,
                'title'=>'请假',
            ],
            [
                'id'=>2,
                'title'=>'其他',
            ]
        ];
        $result = array("total" => count($new_list), "list" => $new_list);
        return json($result);
    }


}
